<?php

namespace App\Http\Controllers\Setting;

use App\Models\Link;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LinksController extends Controller
{
    /** 友链列表 */
    public function index(Request $request)
    {
        $status = $request->input('status');
        if($request->isMethod('post')){
            $model = Link::when(!empty($status),function($query)use($status){
                                $query->where('status',$status);
                            })
                            ->orderBy('updated_at','desc')
                            ->paginate(config('base.limit'));
            return $this->data($model->items(),$model->total());
        }
        return view('setting.links.index',['status'=>$status]);
    }

    /** 编辑 */
    public function edit(Request $request)
    {
        $id = $request->get('id');
        if(empty($id)){
            $model = new Link();
        }else{
            $model = Link::find($id);
        }

        if($request->isMethod('post')){
            $data = $request->all();
            $model->title   = $data['title'];
            $model->link    = $data['link'];
            $model->remark  = $data['remark'];
            $model->contact = $data['contact'];
            $model->save();

            return $this->success('操作成功');
        }
        return view('setting.links.edit',['model'=>$model]);
    }

    /** 上架/下架 */
    public function status(Request $request)
    {
        $id = $request->input('id');
        $status = $request->input('status');

        Link::where(['id'=>$id])->update(['status'=>$status]);

        $msg = $status==1?'上架成功':'下架成功';
        return $this->success($msg);
    }
}
